function getBanner(){
  fetchApi({
    type:"GET",
    apiKey:'GET_INDEX_BANNER',
    successCb:function(data){
      var img = data
      var str = ""
      for(var i =0,l=img.length;i<l;i++){
        str+='<div class="swiper-slide" style="background:url('+host+img[i].firstPageImage+') center center no-repeat"></div>'
      }
      $("#index_banner_box").html(str)
      new Swiper('.first-page', {
        spaceBetween: 0,
        simulateTouch: false,
        loop:true,
        speed: 800,
        nextButton: '.first-page .next',
        prevButton: '.first-page .prev'
      });
    }
  })
}
function getCompanyInfo () {
  fetchApi({
    type:"GET",
    apiKey:'GET_COMPANY_INFO',
    successCb:function(data){
      var markerArr = [{ 
        title: data.companyName_zh,
        content: `地址：${data.companyAddress}<br/>联系电话：${data.companyTel}`,
        point: `${data.longitude}|${data.latitude}`,
        isOpen: 1,
        icon: { w: 23, h: 25, l: 46, t: 21, x: 9, lb: 12}
      }];
      $("#companyName").html(`${data.companyName_zh}<span>${data.companyName_en}</span>`)
      $("#footerCompanyName").html(data.companyName_zh)
      $("#companyAddr").html(data.companyAddress)
      $("#companyTel").html(data.companyTel)
      initMap(markerArr);//创建和初始化地图
    }
  })
}
function getCasesList () {
  fetchApi({
    type:"POST",
    apiKey:'GET_CASES_LIST',
    postData:{page:1,rows:3},
    successCb:function(data){
      var list = data.rows
      var str = ''
      for(var i =0,l=list.length;i<l;i++){
        str+='<a class="img-item" href="project_details.html?id='+list[i].id+'" target="_parent"><div class="mask"><img src="'+host+list[i].firstCaseImage+'"></div><p>'+list[i].caseName+'</p></a>'
      }
      $("#caseeListBox").html(str)
    }
  })
}
function getProductList () {
  fetchApi({
    type:"POST",
    apiKey:'GET_PRODUCT_LIST',
    postData:{page:1,rows:4},
    successCb:function(data){
      var list = data.rows
      var str = ''
      for(var i =0,l=list.length;i<l;i++){
        str+='<a class="img-item" href="product_details.html?id='+list[i].id+'&type='+list[i].productType.id+'" target="_parent"> <div class="mask"> <span class="ani" swiper-animate-effect="fadeInUp" swiper-animate-duration="0.5s">'+list[i].productName+'</span> </div> <img src="'+host+list[i].productImageList[0].imageUrl+'"> </a>'
      }
      $("#productListBox").html(str)
    }
  })
}
function getNewsList () {
  fetchApi({
    type:"POST",
    apiKey:'GET_NEWS_LIST',
    postData:{page:1,rows:4},
    successCb:function(data){
      var list = data.rows
      var str = ''
      for(var i =0,l=list.length;i<l;i++){
        str+='<div class="img-item">'
            +'  <a class="mask" href="new_detail.html?id='+list[i].id+'" target="_parent">'
            +'    <img src="'+host+list[i].informationImage+'">'
            +'  </a>'
            +'  <div class="news-info-box">'
            +'      <a href="#" target="_parent" class="news-title">'+list[i].informationTitle+'</a>'
            +'      <p>'+list[i].informationDescribe+'</p>'
            +'      <span class="news-time">'+list[i].createTime+'</span>'
            +'  </div>'
            +'</div>'
      }
      $("#newsListBox").html(str)
    }
  })
}
function getAboutUs(){
  fetchApi({
    type:"GET",
    apiKey:'GET_ABOUT_INFO',
    successCb:function(data){
      $("#customersImg").attr("src",host+data.customers)
      $("#shouRoomImg").attr("src",host+data.defaultImage)
      $("#aboutUsInfo").html(data.info)
    }
  })
}
function intMainSwiper () {
  return new Swiper('.main-swiper', {
    pagination: '.main-swiper .swiper-pagination',
    paginationClickable: true,
    speed: 800,
    spaceBetween: 0,
    slidesPerView: 1,
    mousewheelControl: true,
    direction: 'vertical',
    onInit: function (swiper) {
      swiperAnimateCache(swiper); //隐藏动画元素 
      swiperAnimate(swiper); //初始化完成开始动画
      $(".top1").click(function(){
        mainSwiper.slideTo(0)
      })
    },
    onSlideChangeStart: function (swiper) {
      swiperAnimate(swiper)
      var $btn = $(".go-next-btn .godown")
      $btn.removeClass('godown1 hide')
      $(".main-swiper").removeClass("top-100")
      mainSwiper.enableMousewheelControl()
      switch (parseInt(swiper.activeIndex)) {
        case 0:
          $btn.addClass('godown1')
          break
        case 5:
          $btn.addClass('hide')
          if (navigator.userAgent.indexOf("Firefox")>0) {
            mainSwiper.disableMousewheelControl()
          }
      }
    }
  })
}
getBanner()
var mainSwiper = intMainSwiper()
var postCodeCheck = null;
$(window).ready(function () {
  getAboutUs()
  getCompanyInfo()
  getCasesList()
  getNewsList()
  getProductList()
  function isNull($this) {
    $this.siblings(".error-box").removeClass("show")
    if ($this.val() === '') {
      $this.siblings(".error-box").eq(0).addClass("show")
      return true
    } else {
      $this.siblings(".error-box").eq(0).removeClass("show")
      return false
    }
  }
  function isPhone($this) {
    var value = $this.val()
    !(/^1[34578]\d{9}$/.test(value))
      ? $this.siblings(".error-box").addClass("show")
      : $this.siblings(".error-box").removeClass("show")
  }
  function isEmail($this) {
    var value = $this.val()
    var reg = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
    !reg.test(value)
      ? $this.siblings(".error-box").addClass("show")
      : $this.siblings(".error-box").removeClass("show")
  }
  function isCode () {
    var $this = $("#form_code")
    var value = $this.val()
    if(value == ''){
      $this[0].focus()
      return
    }
    $this.siblings(".error-box").removeClass("show")
    if(!postCodeCheck){
      $this.siblings(".code-error-box").addClass("show")
    }
    value != postCodeCheck
      ? $this.siblings(".code-error-box").addClass("show")
      : $this.siblings(".code-error-box").removeClass("show")
  }
  function getPostCode(){
    $.ajax({
      type: 'GET',
      url: ajaxUrlObj['GET_POST_CODE'],
      success: function(rep){
        if (typeof rep === 'string') {
          rep = JSON.parse(rep)
        }
        if (rep.code == 1){
          rep = JSON.parse(rep.data)
          $("#postCodeImg").attr("src",rep.url).removeClass("hide");
          postCodeCheck = rep.value
        }
      },
      error: function(error){
        console.log(error)
      }
    })
  }
  function onMouseScroll(e) {
    e.preventDefault();
    var $target = $(e.target)
    var isEndPage = $target.hasClass("slide6") || $target.parents(".slide6")[0]
    var wheel = e.originalEvent.wheelDelta || -e.originalEvent.detail;
    var delta = Math.max(-1, Math.min(1, wheel));
    if (delta < 0) {//向下滚动
      if (mainSwiper.isEnd && isEndPage) {
        $(".main-swiper").addClass("top-100")
        mainSwiper.disableMousewheelControl()
      }
    } else {//向上滚动
      if (navigator.userAgent.indexOf("Firefox")>0 && !$(".main-swiper").hasClass('top-100')) {
        mainSwiper.slidePrev()
        mainSwiper.enableMousewheelControl()
      }
      $(".main-swiper").removeClass("top-100")
      if(navigator.userAgent.indexOf("Firefox")<=0){
        mainSwiper.enableMousewheelControl()
      }
      
      
    }
  }
  $(".form-box .is-required").on("blur", function () {
    var $this = $(this)
    isNull($this)
  })
  $("#form_phone").on("change", function () {
    var $this = $(this)
    isPhone($this)
  })
  $("#form_email").on("change", function () {
    var $this = $(this)
    isEmail($this)
  })
  $("#form_code").one("focus",function(){
    getPostCode()
  })
  $("#postCodeImg").on("click",function(){
    getPostCode()
  })
  $("#submitForm").on("click", function () {
    isNull($("#form_text"))
    isNull($("#form_code"))
    isCode()
    var errorNum = $(".error-box.show").length
    if (errorNum > 0) {
      return
    }
    $.ajax({
      type: 'POST',
      url: ajaxUrlObj['POST_MESSAGE'],
      data: {
        content:$("#form_text").val(),
        customerName:$("#form_name").val(),
        tel:$("#form_phone").val(),
        email:$("#form_email").val(),
      },
      success: function(rep){
        if (typeof rep === 'string') {
          rep = JSON.parse(rep)
        }
        $(".toast-box .toast-body").html(rep.code == 1?'反馈成功':'反馈失败')
        if (rep.code != 1) {
          $(".toast-box").addClass("error-toast")
        }
        $(".toast-box").removeClass("hide");
         setTimeout(function(){
          $(".toast-box").addClass("hide").removeClass("error-toast");
         }, 1500);
      },
      error: function(error){
        console.log(error)
      }
    });
  })
  $(document).on('mousewheel DOMMouseScroll', onMouseScroll);
})



//标注点数组
var markerArr = []
//创建和初始化地图函数：

function initMap(marker) {
  markerArr = marker
  createMap();//创建地图
  setMapEvent();//设置地图事件
  addMapControl();//向地图添加控件
  addMarker();//向地图中添加marker
}

//创建地图函数：
function createMap() {
  var map = new BMap.Map("dituContent");//在百度地图容器中创建一个地图
  var point = new BMap.Point(113.328415, 23.131355);//定义一个中心点坐标
  map.centerAndZoom(point, 17);//设定地图的中心点和坐标并将地图显示在地图容器中
  window.map = map;//将map变量存储在全局
}

//地图事件设置函数：
function setMapEvent() {
  map.enableDragging();//启用地图拖拽事件，默认启用(可不写)
  map.enableScrollWheelZoom();//启用地图滚轮放大缩小
  map.enableDoubleClickZoom();//启用鼠标双击放大，默认启用(可不写)
  map.enableKeyboard();//启用键盘上下左右键移动地图
}

//地图控件添加函数：
function addMapControl() {
  //向地图中添加缩放控件
  var ctrl_nav = new BMap.NavigationControl({ anchor: BMAP_ANCHOR_TOP_LEFT, type: BMAP_NAVIGATION_CONTROL_LARGE });
  map.addControl(ctrl_nav);
  //向地图中添加缩略图控件
  var ctrl_ove = new BMap.OverviewMapControl({ anchor: BMAP_ANCHOR_BOTTOM_RIGHT, isOpen: 0 });
  map.addControl(ctrl_ove);
  //向地图中添加比例尺控件
  var ctrl_sca = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_BOTTOM_LEFT });
  map.addControl(ctrl_sca);
}


//创建marker
function addMarker() {
  for (var i = 0; i < markerArr.length; i++) {
    var json = markerArr[i];
    var p0 = json.point.split("|")[0];
    var p1 = json.point.split("|")[1];
    var point = new BMap.Point(p0, p1);
    var iconImg = createIcon(json.icon);
    var marker = new BMap.Marker(point, { icon: iconImg });
    var iw = createInfoWindow(i);
    var label = new BMap.Label(json.title, { "offset": new BMap.Size(json.icon.lb - json.icon.x + 10, -20) });
    marker.setLabel(label);
    map.addOverlay(marker);
    label.setStyle({
      borderColor: "#808080",
      color: "#333",
      cursor: "pointer"
    });
    (function () {
      var index = i;
      var _iw = createInfoWindow(i);
      var _marker = marker;
      _marker.addEventListener("click", function () {
        this.openInfoWindow(_iw);
      });
      _iw.addEventListener("open", function () {
        _marker.getLabel().hide();
      })
      _iw.addEventListener("close", function () {
        _marker.getLabel().show();
      })
      label.addEventListener("click", function () {
        _marker.openInfoWindow(_iw);
      })
      if (!!json.isOpen) {
        label.hide();
        _marker.openInfoWindow(_iw);
      }
    })()
  }
}
//创建InfoWindow
function createInfoWindow(i) {
  var json = markerArr[i];
  var iw = new BMap.InfoWindow("<b class='iw_poi_title' title='" + json.title + "'>" + json.title + "</b><div class='iw_poi_content'>" + json.content + "</div>");
  return iw;
}
//创建一个Icon
function createIcon(json) {
  var icon = new BMap.Icon("http://app.baidu.com/map/images/us_mk_icon.png", new BMap.Size(json.w, json.h), { imageOffset: new BMap.Size(-json.l, -json.t), infoWindowOffset: new BMap.Size(json.lb + 5, 1), offset: new BMap.Size(json.x, json.h) })
  return icon;
}
